package artid.com.arttogoa.util;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import artid.com.arttogoa.app.ArtWorkApp;
import artid.com.arttogoa.barcode.Bimp;
import artid.com.arttogoa.barcode.Cache;
import artid.com.arttogoa.parser.AppItem;
import artid.com.arttogoa.parser.MySellInfoParser;
import artid.com.arttogoa.parser.MySellInfo_ImageBean;
import artid.com.arttogoa.volley.VolleyBasic;
import artid.com.arttogoa.volley.VolleyCallback;
import artid.com.arttogoa.volley.VolleyData;
import artid.com.arttogoa.volley.VolleyMap;
import com.android.volley.VolleyError;

public class UploadTheSaleOfGoodsUtils {
	private MySellInfoParser mp;
	private Activity mContext;
	private int goodstype;
	private String goods_id;
	private int is_weight = 0;
	public UploadTheSaleOfGoodsUtils(Activity mContext, MySellInfoParser mp,
									 int goodstype) {
		this.mp = mp;
		this.mContext = mContext;
		this.goodstype = goodstype;
//		Upload();
	}

	public void Upload() {
		// TODO Auto-generated method stub
		AlertUtils.initloadAlertDialog(mContext, mContext.getWindowManager()
				.getDefaultDisplay().getWidth(), "正在上传商品信息...");
		comNetwork();
	}

	/**
	 * 发布或编辑商品
	 */
	private void comNetwork() {

		// TODO Auto-generated method stub
		String uri = Cache.publishGoods;
		// System.out.println("params=" + params.toString());

		VolleyBasic.getInstance(mContext).post(false, false, uri,
				VolleyMap.getInstance().publishGoods(mp, goodstype),
				AppItem.class, new VolleyCallback() {

					public void onSuccess(VolleyData vd) {

						// TODO
						// Auto-generated
						// method stub
						Log.i("发布或编辑商品", "请求结果：" + vd.getJson());
						try {
							JSONObject jo = new JSONObject(vd.getJson());
							if (vd.getCode() != 0) {

								goods_id = jo.optJSONObject("data").optString(
										"goods_id");
								String state = jo.optJSONObject("data")
										.optString("state");
								if (TextUtils.isEmpty(state)
										|| TextUtils.isEmpty(goods_id)) {
									AlertUtils.dismiss();
									Toast.makeText(mContext, "上传失败！", 2).show();
								} else {
									mib = mp.getGoods_image();
									if (goodstype == Bimp.GOODS_PUBLISH) {// 发布商品
										if (mp.getIs_auth().equals("1")) {// 发布备案商品
											is_weight = 2;
										} else {// 发布拍照商品
											is_weight = 0;
										}
										if (mib.size() < 1) {
											AlertUtils
													.initUploadAlertDialog(
															mContext,
															mContext.getWindowManager()
																	.getDefaultDisplay()
																	.getWidth(),
															" ");
											AlertUtils.setGoodsImage(true,
													goodstype);
											Handler handler1 = new Handler();
											handler1.postDelayed(
													new Runnable() {
														@Override
														public void run() {
															Message msg = new Message();
															msg.what = 3;
															handler.sendMessage(msg);
														}
													}, 2000);
										} else {

											new Thread(micNetworkTask).start();
										}
									} else if (goodstype == Bimp.GOODS_EDIT) {// 编辑商品
										if (mp.getIs_auth().equals("1")) {// 备案商品编辑
											is_weight = 2;

										} else {// 拍照商品编辑
											is_weight = 0;
										}
										deleteIds = mp.getDelete_image_ids();
										if (deleteIds != null
												&& deleteIds.size() > 0) {
											deleteImg();
										} else {
											if (mib.size() < 1) {
												AlertUtils
														.initUploadAlertDialog(
																mContext,
																mContext.getWindowManager()
																		.getDefaultDisplay()
																		.getWidth(),
																" ");
												AlertUtils.setGoodsImage(true,
														goodstype);
												Handler handler1 = new Handler();
												handler1.postDelayed(
														new Runnable() {
															@Override
															public void run() {
																Message msg = new Message();
																msg.what = 3;
																handler.sendMessage(msg);
															}
														}, 2000);
											} else {
												new Thread(micNetworkTask)
														.start();
											}
											// new
											// Thread(micNetworkTask).start();
										}
									}
								}
							} else {
								ToastUtil.toast(mContext, "出售商品失败，请重试");
								VolleyBasic.disMissLoding();
								AlertUtils.dismiss();
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					public void onError(VolleyError volleyError) {
						AlertUtils.dismiss();
					}
				});
	}

	/**
	 * 删除商品图片
	 */
	private void deleteImg() {

		// TODO Auto-generated method stub
		String uri = Cache.delgoodsimg;
		// System.out.println("params=" + params.toString());

		VolleyBasic.getInstance(mContext).post(false, false, uri,
				VolleyMap.getInstance().delgoodsimg(deleteIds), AppItem.class,
				new VolleyCallback() {
					public void onSuccess(VolleyData vd) {

						// TODO
						// Auto-generated
						// method stub
						Log.i("发布或编辑商品", "请求结果：" + vd.getJson());
						try {
							JSONObject jo = new JSONObject(vd.getJson());
							String state = jo.optJSONObject("data").optString(
									"state");
							if (TextUtils.isEmpty(state)) {
								AlertUtils.dismiss();
								Toast.makeText(mContext, "上传失败！", 2).show();
							} else {
								if (mib.size() < 1) {
									AlertUtils.initUploadAlertDialog(mContext,
											mContext.getWindowManager()
													.getDefaultDisplay()
													.getWidth(), " ");
									AlertUtils.setGoodsImage(true, goodstype);
									Handler handler1 = new Handler();
									handler1.postDelayed(new Runnable() {
										@Override
										public void run() {
											Message msg = new Message();
											msg.what = 3;
											handler.sendMessage(msg);
										}
									}, 2000);
								} else {
									new Thread(micNetworkTask).start();
								}
							}

						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					public void onError(VolleyError volleyError) {
						AlertUtils.dismiss();
					}
				});
	}

	private List<MySellInfo_ImageBean> mib;
	private List<String> deleteIds;
	/**
	 * 上传商品图片
	 */
	Runnable micNetworkTask = new Runnable() {

		@Override
		public void run() {
			// TODO
			/**
			 * 变更进度条
			 */
			Message loadMsg = new Message();
			loadMsg.what = 0;
			handler.sendMessage(loadMsg);
			/**
			 * 在这里进行 上传商品图片.网络请求相关操作
			 */
			for (int i = 0; i < mib.size(); i++) {
				MySellInfo_ImageBean mb = mib.get(i);
				Map<String, File> files = new HashMap<String, File>();
				files.put("goods_image", new File(mb.getGoods_image()));

				Map<String, String> params = new HashMap<String, String>();
				params.put("token", AppUtil.getUser().getToken());
				params.put("goods_id", goods_id);
				params.put("is_file", "2");
				params.put("is_weight", String.valueOf((i + 1)));
				params.put("image_width", String.valueOf(mb.getImage_width()));
				params.put("image_height", String.valueOf(mb.getImage_height()));
				params.put("is_auth", mp.getIs_auth());
				System.out.println(params.toString());
				String uri = Cache.goodsPicture;
				try {
					String Response = post(uri, params, files);
					if (TextUtils.isEmpty(Response)) {
						Message errorMsg = new Message();
						errorMsg.what = -1;
						handler.sendMessage(errorMsg);
						break;
					}
					System.out.println("Response=" + Response);
					Message responseMsg = new Message();
					Bundle data = new Bundle();
					data.putString("value", Response);
					data.putInt("index",i);
					responseMsg.setData(data);
					responseMsg.what = 1;
					handler.sendMessage(responseMsg);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		}
	};

	public String post(String url, Map<String, String> params,
					   Map<String, File> files) throws IOException {
		String BOUNDARY = java.util.UUID.randomUUID().toString();
		String PREFIX = "--", LINEND = "\r\n";
		String MULTIPART_FROM_DATA = "multipart/form-data";
		String CHARSET = "UTF-8";
		URL uri = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
		conn.setConnectTimeout(80 * 1000);
		conn.setReadTimeout(80 * 1000); // 缓存的最长时间
		conn.setDoInput(true);// 允许输入
		conn.setDoOutput(true);// 允许输出
		conn.setUseCaches(false); // 不允许使用缓存
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Charsert", "UTF-8");
		conn.setRequestProperty("connection", "keep-alive");
		conn.setRequestProperty("Accept",
				"application/json, text/javascript, */*");
		conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
		conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
				+ ";boundary=" + BOUNDARY);
		conn.setChunkedStreamingMode(1024);
		// 首先组拼文本类型的参数
		StringBuilder sb = new StringBuilder();
		for (Map.Entry<String, String> entry : params.entrySet()) {
			sb.append(PREFIX);
			sb.append(BOUNDARY);
			sb.append(LINEND);
			sb.append("Content-Disposition: form-data; name=\""
					+ entry.getKey() + "\"" + LINEND);
			// sb.append("Content-Type: text/plain; charset=" + CHARSET +
			// LINEND);
			// sb.append("Content-Transfer-Encoding: utf-8" + LINEND);
			sb.append(LINEND);
			sb.append(entry.getValue());
			sb.append(LINEND);
		}
		DataOutputStream outStream = new DataOutputStream(
				conn.getOutputStream());

		outStream.write(sb.toString().getBytes());
		// 发送文件数据
		int length = 0;
		if (files != null)
			for (Map.Entry<String, File> file : files.entrySet()) {
				StringBuilder sb1 = new StringBuilder();
				sb1.append(PREFIX);
				sb1.append(BOUNDARY);
				sb1.append(LINEND);
				sb1.append("Content-Disposition: form-data; name=\""
						+ file.getKey() + "\"; filename=\""
						+ file.getValue().getName() + "\"" + LINEND);
				sb1.append("Content-Type: application/octet-stream; charset="
						+ CHARSET + LINEND);
				sb1.append(LINEND);
				outStream.write(sb1.toString().getBytes());

				InputStream is = new FileInputStream(file.getValue());
				long total = is.available();
				System.out.println("图片的data大小==============" + total);
				byte[] buffer = new byte[1024];
				int len = 0;

				while ((len = is.read(buffer)) != -1) {

					outStream.write(buffer, 0, len);
					length += len;
					Message msg = new Message();
					msg.what = 2;
					msg.obj = (int) ((length / (float) total) * 100);
					handler.sendMessage(msg);
				}
				is.close();
				outStream.write(LINEND.getBytes());

			}
		System.out.println(outStream.toString());
		// 请求结束标志
		byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
		outStream.write(end_data);
		outStream.flush();
		// 得到响应码
		StringBuilder sb2 = null;
		try {
			int res = conn.getResponseCode();
			InputStream in = conn.getInputStream();
			sb2 = new StringBuilder();
			if (res == 200) {
				int ch;
				while ((ch = in.read()) != -1) {
					sb2.append((char) ch);
				}
			}
		} catch (SocketTimeoutException e) {
			// TODO: handle exception
			e.printStackTrace();

			return "";
		}

		outStream.close();
		conn.disconnect();
		return sb2.toString();
	}
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
				case -1:// 图片上传超市
					ToastUtil.toast(mContext, "连接超时，请重新请求");
					AlertUtils.dismiss();
					break;
				case 0:// 更新进度条
					AlertUtils.initUploadAlertDialog(mContext, mContext
									.getWindowManager().getDefaultDisplay().getWidth(),
							"正在上传第1张商品图片");
					break;
				case 1:// 上传图片返回结果处理
					Bundle data = msg.getData();
					String val = data.getString("value");
					int type = data.getInt("type");
					if (!TextUtils.isEmpty(val)) {
						val = val.substring(val.indexOf("{"),
								val.lastIndexOf("}") + 1);
						val = NetUtils.decodeUnicode(val);
						try {
							JSONObject jo = new JSONObject(val);
							if (jo.optJSONObject("data").optString("state")
									.equals("1")) {
								int index = data.getInt("index");
								System.out.println("index=" + index);
								if (index == mib.size() - 1) {
									AlertUtils.setGoodsImage(true, goodstype);
									Handler handler1 = new Handler();
									handler1.postDelayed(new Runnable() {
										@Override
										public void run() {
											Message msg = new Message();
											msg.what = 3;
											handler.sendMessage(msg);
										}
									}, 2000);
								} else {
									AlertUtils.setText("正在上传第" + (index + 2)
											+ "张商品图片");
								}

							} else {
								AlertUtils.setGoodsImage(false, goodstype);
								Handler handler1 = new Handler();
								handler1.postDelayed(new Runnable() {
									@Override
									public void run() {
										Message msg = new Message();
										msg.what = 4;
										handler.sendMessage(msg);
									}
								}, 2000);
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							AlertUtils.disMissLoding();
							AlertUtils.dismiss();
						}
					}
					break;
				case 2:// 更新进度条进度
					int i = (Integer) msg.obj;
					AlertUtils.setProgressBar(i);
					break;
				case 3:// 发布或编辑成功
					if (goodstype == Bimp.GOODS_PUBLISH) {// 发布商品
						// 通知刷新出售中数据
						Intent intent2 = new Intent("com.MySell_fragment.receiver");
						intent2.putExtra("intentActivity", "艺术品出售");
						mContext.sendBroadcast(intent2);
						if(ArtWorkApp.activityList.size()>1) {
							if(!ArtWorkApp.activityList.get(ArtWorkApp.activityList.size() - 1).getComponentName().getClassName().equals(mContext.getApplicationContext().getPackageName()+"MainActivity")){
								ArtWorkApp.getInstance().exit(ArtWorkApp.activityList.size() - 1);
							}
						}
						mContext.finish();
					} else if (goodstype == Bimp.GOODS_EDIT) {// 编辑商品
						// 通知显示出售中页面
						Intent intent = new Intent("com.MySell_Activity.receiver");
						intent.putExtra("intentActivity", "我出售的详情-编辑");
						intent.putExtra("retrunActivity", 0);
						mContext.sendBroadcast(intent);
						// 通知刷新出售中数据
						Intent intent2 = new Intent("com.MySell_fragment.receiver");
						intent2.putExtra("intentActivity", "我出售的详情-编辑");
						mContext.sendBroadcast(intent2);
						if(ArtWorkApp.activityList.size()>1) {
							if(!ArtWorkApp.activityList.get(ArtWorkApp.activityList.size() - 1).getComponentName().getClassName().equals(mContext.getApplicationContext().getPackageName()+"MainActivity")){
								ArtWorkApp.getInstance().exit(ArtWorkApp.activityList.size() - 1);
							}
						}
						mContext.finish();
					}
					break;
				case 4:// 发布或编辑失败
					if (goodstype == Bimp.GOODS_PUBLISH) {// 发布商品

					} else if (goodstype == Bimp.GOODS_EDIT) {// 编辑商品

					}
					break;
			}
		}
	};
}
